package com.mmall.service.impl;

import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FTPUtil;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by JINPENG on 2018/10/23.
 */
@Service("iFileService")
public class FileServiceImpl implements IFileService{
    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    public  String upload(MultipartFile file,String path) {
        String fileName = file.getOriginalFilename();
        //获取拓展名
        String  fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadFileName = UUID.randomUUID().toString() + "." + fileExtensionName;
        logger.info("开始上传文件，上传文件名为:{}，上传路径:{},新文件名:{}", fileName, path, uploadFileName);
        File filedir = new File(path);
        if (!filedir.exists()) {
            filedir.setWritable(true);
            filedir.mkdirs();
        }
        File targetFile = new File(path, uploadFileName);
        try {
            //spring 的上传文件到服务器磁盘
            file.transferTo(targetFile);
            //将targetFile 上传到Ftp 服务器中
            //上传完成之后，删除upload下面的文件
            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            targetFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  targetFile.getName();
    }
}
